import React, { useEffect, useState } from 'react';
/* 引入antd */
import { Table, Button, Modal, Input, Space } from 'antd';
/* 引入上下文 */
import useStore from "../../../context/useStore";

import { useObserver } from 'mobx-react-lite';

const { confirm } = Modal;

const ClassifyQuestions: React.FC = () => {


  const { questions } = useStore()

  useEffect(() => {
    questions.getQuestionsTypeAction();
  }, [questions]);

  
  const columns = [
    {
      title: '类型iD',
      dataIndex: 'questions_type_id',
      key: 'questions_type_sort',
      render: (text: React.ReactNode) => <span>{text}</span>,
    },
    {
      title: '类型名称',
      dataIndex: 'questions_type_text',
      key: 'questions_type_sort',
    },
    {
      title: '操作',
      key: 'action',
      render: (record: any) => (
        <Space size="middle">
          <button onClick={() => { delType(record.questions_type_id) }}>删除</button>
        </Space>
      ),
    }
  ]

  /* 对话框开关 */
  const [visible, setVisible] = useState<boolean>(false);
  /* 保存input框输入内容 */
  const [addText, setAddText] = useState<string>('');



  /* 点击弹出对话框 */
  function showModal() {
    setVisible(true)
  };

  /* 点击确定 */
  function handleOk() {
    /* 添加sort值 */
    const num = questions.questionsTypeList.length + 1;
    /* 把创建的sort值从number转为string类型 */
    let sort = String(num);
    /* 调用添加试题类型接口 */
    questions.getAddInsertQuestionsTypeAction(addText, sort);
    setVisible(false)
  };

  /* 点击取消 */
  function handleCancel() {
    /* 清空输入框 */
    setAddText('');
    setVisible(false)
  };

  /* input输入框 */
  function getValue(e: any) {
    /* console.log('====================================');
    console.log('getValue..',e.target.value);
    console.log('===================================='); */

    setAddText(e.target.value);
  };

  /* 点击删除 */
  function delType(id: string) {
   
    confirm({
      title: '确定要删除吗?',
      onOk() {
        questions.delQuestionsTypeAction(id);
      },
      onCancel() { },
      okText:"确定", 
      cancelText:"取消"
    });
  }


  return useObserver(() => <div>
    <h2>试题分类</h2>
    <div>
      <Button type="primary" onClick={showModal} style={{marginBottom:20}}>
        +添加类型
        </Button>
      <Table rowKey={columns[0].key} columns={columns} dataSource={questions.questionsTypeList} />
    </div>
    <>
      <Modal
        title="创建新类型"
        visible={visible}
        onOk={handleOk}
        onCancel={handleCancel}
        okText="确认"
        cancelText="取消"
      >
        <Input placeholder="请输入类型名称" value={addText} onChange={getValue} />
      </Modal>
    </>
  </div>

  );
}

export default ClassifyQuestions
